4

fetch结合(async函数来使用)

<ul id="students">
</ul>

ajax请求

function ajax(url){
    
          let xmlHttp=new XMLHttpRequest();
            xmlHttp.open("get",url,true);
            xmlHttp.onreadystatechange=function(){
                if(xmlHttp.readyState==4&&xmlHttp.status==200){
                    let data= JSON.parse(xmlHttp.responseText);
                    console.log(data);
                }
            }
            xmlHttp.send(null);
}

ajax(url);
let uldom=document.getElementById("students");

let url="http://192.168.0.46:8000/student.json";

对于使用fetch可以方便很多,这就是下面要使用的fetch的代码,先熟悉了解下:

/*fetch(url).then(respone=>{
    //return respone.text();
    return respone.json();
}).then(data=>{
    console.log(data);
})*/

使用fetch


//获取css里ul的id属性
 let uldom=document.getElementById("students");
//单独创建一个json文件,获取地址
let url="http://192.168.0.46:8000/student.json";

function main(){
    fetch(url).then(respone=>{
    //return respone.text();
    return respone.json();
}).then(students=>{

    let html=``;
    for(let i=0,l=students.length;i<l;i++){
        let name=students[i].name;
        let age=students[i].age;
        html+= `
        <li>姓名${name},年龄${age}</li>
    `
    }

    uldom.innerHTML=html;
});

    
}
main();

最终代码

let uldom=document.getElementById("students");
let url="http://192.168.0.46:8000/student.json";

  async function main(){
        let respone = await fetch(url);
        let students = await respone.json();

    let html=``;
    for(let i=0,l=students.length;i<l;i++){
        let name=students[i].name;
        let age=students[i].age;
        html+= `
        <li>姓名${name},年龄${age}</li>
    `
    }
    uldom.innerHTML=html;
  }
main();

这是我的json文件里的代码:

[
    {"name":"ss","age":"3"},
    {"name":"aa","age":"1"},
    {"name":"qq","age":"4"},
    {"name":"zz","age":"3"},
    {"name":"xx","age":"5"},
    {"name":"cc","age":"7"}
]

最后结果:

姓名ss,年龄3
姓名aa,年龄1
姓名qq,年龄4
姓名zz,年龄3
姓名xx,年龄5
姓名cc,年龄7

师妹儿
195 声望9 粉丝

html/css/html5/javascript/jquery/es6/svg